// set function parseTime,formatTime to filter
export { parseTime, formatTime } from '@/utils'

function pluralize(time, label) {
  if (time === 1) {
    return time + label
  }
  return time + label + 's'
}

export function timeAgo(time) {
  const between = Date.now() / 1000 - Number(time)
  if (between < 3600) {
    return pluralize(~~(between / 60), ' minute')
  } else if (between < 86400) {
    return pluralize(~~(between / 3600), ' hour')
  } else {
    return pluralize(~~(between / 86400), ' day')
  }
}

/* 数字 格式化*/
export function numberFormatter(num, digits) {
  const si = [
    { value: 1E18, symbol: 'E' },
    { value: 1E15, symbol: 'P' },
    { value: 1E12, symbol: 'T' },
    { value: 1E9, symbol: 'G' },
    { value: 1E6, symbol: 'M' },
    { value: 1E3, symbol: 'k' }
  ]
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      return (num / si[i].value + 0.1).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
    }
  }
  return num.toString()
}

export function toThousandFilter(num) {
  return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}

// 四舍五入并保留两位小数
export function floorTwoDecimal(x) 
{ 
　　var f_x = parseFloat(x); 
　　if (isNaN(f_x)) 
　　{ 
　　　　return 0; 
　　} 
　　var f_x = Math.round(x*100)/100; 
　　var s_x = f_x.toString(); 
　　var pos_decimal = s_x.indexOf('.'); 
　　if (pos_decimal < 0) 
　　{ 
　　　　pos_decimal = s_x.length; 
　　s_x += '.'; 
　　} 
　　while (s_x.length <= pos_decimal + 2) 
　　{ 
　　　　s_x += '0'; 
　　} 
　　return s_x; 
}

// 对内容进行掩码打星
export function maskStr(str) {
  if (str) {
    let newStr
    if (str.length === 1) {
      newStr = '*'
    } else if (str.length === 2) {
      newStr = str.substr(0, 1) + '*'
    } else if (str.length > 2) {
      let char = ''
      for (let i = 0, len = str.length - 2; i < len; i++) {
        char += '*'
      }
      newStr = str.substr(0, 1) + char + str.substr(-1, 1)
    } else {
      newStr = str
    }

    return newStr
  } else {
    return undefined
  }
}